package club.baimahu.pencil.domain.entity.event;

import club.baimahu.pencil.domain.entity.account.AccountManager;
import club.baimahu.pencil.exception.BuyException;
import club.baimahu.pencil.domain.entity.Supplier;
import club.baimahu.pencil.domain.entity.VirtualSupplierFactory;
import club.baimahu.pencil.domain.session.GoodsStock;
import club.baimahu.pencil.domain.session.Replenishment;
import club.baimahu.pencil.domain.session.SimpleGoodFactory;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;

@Slf4j
public class ShortOfStockEventListener  extends AbstractStockEventListener{

    //Queue<Runnable> runnableQueue = new LinkedBlockingDeque<>(10);



    @Override
    public void onEvent(StockEvent stockEvent) {
        if(stockEvent != null && stockEvent instanceof StockShortOfEvent){
            Replenishment replenishment = (Replenishment)stockEvent.source();

            AccountManager accountManager = replenishment.getAccountManager();
            GoodsStock goodsStock = replenishment.getGoodsStock();

            //前台连续触发两个库存短缺事件后，补库存也会触发两次，但是库存被第一次补充好之后，第二次库存已不短缺，按道理不该再补充
            if(!SimpleGoodFactory.isShortOf(goodsStock)){
                log.info("商品{}库存充足，撤销补库存",goodsStock.getGoods().getGoodsNo());
                return;
            }

            BigDecimal factoryPrice = goodsStock.getGoods().getFactoryPrice();
            BigDecimal shouldPay = factoryPrice.multiply(new BigDecimal(goodsStock.getBuyAmount())) ;

            if(accountManager.getBalance().doubleValue() < shouldPay.doubleValue()){
                throw new BuyException("账户余额不足，不足以补库存");
            }

            //虚拟万能供应商
            Supplier supplier = VirtualSupplierFactory.getVirtualSupplier();
            // 付款给供应商
            boolean success = accountManager.pay(shouldPay,supplier);
            if(success){
                goodsStock.getAtomicAmount().addAndGet(goodsStock.getBuyAmount());
                log.info("商品{}补库存{}件，账户扣减成功,支出{}元",goodsStock.getGoods().getGoodsNo(),goodsStock.getBuyAmount(),shouldPay.doubleValue());
            }else{
                throw new BuyException("账户付款失败");
            }


        }
    }
}
